package com.ingenieria.industrial.service.implementacion;

import com.cerd.util.BaseSP01.JUtilBaseSP01;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;

public abstract class BaseService extends JUtilBaseSP01 implements Serializable{
    
    protected int pages = -1;
    protected Connection transact;      // CONEXION QUE SE VA A USAR PARA LAS OPERACIONES QUE REQUIERAN TRANSACCION
    protected int pos = -1;

    protected abstract void initDAO() throws SQLException;

    protected abstract void begin() throws SQLException;

    public void begin(Connection cnx) throws SQLException {
        if (cnx != null) {
            transact = cnx;
            transact.setAutoCommit(false);
            initDAO();
        }
    }

    public void commit() throws SQLException {
        if (transact != null && !transact.isClosed()) {
            transact.commit();
        }
    }

    public void handleRelease() {
        try {
            if (transact != null && !transact.isClosed()) {
                transact.close();
                transact = null;
            }
        } catch (SQLException sos) {
        }
    }

    public void handleRelease(Connection cnx) {
        try {
            if (cnx != null && !cnx.isClosed()) {
                cnx.close();
            }
        } catch (SQLException sos) {
        }
    }

    public Exception handleError(Exception sos) throws Exception {
        return handleError(sos, transact);
    }

    public Exception handleError(Exception sos, Connection cnx) throws Exception {
        try {
            if (cnx != null && !cnx.isClosed() && !cnx.getAutoCommit()) {
                cnx.rollback();
            }
        } catch (SQLException help) {
        }

        if (sos instanceof Exception) {
            throw (Exception) sos;
        }
        throw new Exception(sos.getMessage());
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public int getPos() {
        return pos;
    }

    public void setPos(int pos) {
        this.pos = pos;
    }
}
